package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @Author: Bin
 * @description:
 * @date: 2025-07-14 20:04
 */
@Component
public class RedisIdWorker {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final long COUNT_BITS = 32;

    private static final long BEGIN_TIMESTAMP = 1640995200L;

    public long nextId(String keyPrefix) {
        LocalDateTime now = LocalDateTime.now();
        long epochSecond = now.toEpochSecond(ZoneOffset.UTC);
        // 中间31位时间戳
        long timestamp = epochSecond - BEGIN_TIMESTAMP;
        // 后32位自增数
        LocalDateTime nowTime = LocalDateTime.now();
        String dataTime = nowTime.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + dataTime);

        return timestamp << COUNT_BITS | count;
    }

}
